package it.storm.solution;

/**
 * 463. 岛屿的周长
 * https://leetcode-cn.com/problems/island-perimeter/
 */
public class Solutions_463 {
    public static void main(String[] args) {
        int grid[][] = {{0, 1, 0, 0},
                        {1, 1, 1, 0},
                        {0, 1, 0, 0},
                        {1, 1, 0, 0}};  // output: 16

        int result = islandPerimeter(grid);
        System.out.println(result);
    }

    public static int islandPerimeter(int[][] grid) {
        int row = grid.length;
        if (row < 1) {
            return 0;
        }
        int col = grid[0].length;
        int res = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 1) {
                    // 出现岛屿时，直接加周长 4
                    res += 4;
                    if (i > 0 && grid[i - 1][j] == 1) {
                        // 若当前岛屿的上方也是岛屿，那么需要从 res 中减两条边
                        res -= 2;
                    }
                    if (j > 0 && grid[i][j - 1] == 1) {
                        // 若当前岛屿的左边也是岛屿，那么需要从 res 中减两条边
                        res -= 2;
                    }
                }
            }
        }
        return res;
    }
}
